package com.dai.rpc.compress;

import com.dai.rpc.constant.CompressTypeEnum;
import com.dai.rpc.exceptions.MyRpcException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPCompress implements Compress{

    @Override
    public String name() {
        return CompressTypeEnum.GZIP.getName();
    }

    @Override
    public byte[] compress(byte[] bytes) {
        // 压缩数据
        if(bytes == null) throw new NullPointerException("传入的压缩数据为null");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
            gzipOutputStream.write(bytes);
            gzipOutputStream.flush();
            gzipOutputStream.finish();
            return outputStream.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
            throw new MyRpcException("压缩数据出错",e);
        }
    }

    @Override
    public byte[] decompress(byte[] bytes) {
        // 解压数据
        if(bytes == null) throw new NullPointerException("传入的解压数据为null");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try{
            GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(bytes));
            byte[] buffer = new byte[1024 * 4];
            int n;
            while((n = gzipInputStream.read(buffer)) > -1){
                outputStream.write(buffer, 0, n);
            }
            return outputStream.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
            throw new MyRpcException("解压数据出错",e);
        }

    }
}
